const app = getApp();
const TIM = require('../../utils/tim-wx.js');
let onMessageReceived; //监听新消息推送
let onMessageReadByPeer; //监听已读回执
import { emojiUrl, emojiMap, emojiName, tackleEmojiMessage } from "../../utils/emoji.js";

Page({
    data: {
        pageOnHide: false, //页面是否切后台
        pageOnHideNewMessage: false, //页面切后台时是否收到新消息
        emojiUrl: emojiUrl,
        emojiMap: emojiMap,
        emojiName: emojiName,
        showEmojiBox: false, //显示选择表情
        conversationID: '', //消息所属的会话ID
        userID: '', //对方userID
        nextReqMessageID: '', //用于分页续拉的消息ID
        isCompleted: '', //消息是否全部加载
        messageList: [], //消息列表
        msgContent: '', //输入的消息
        setFocus: false, //输入框获取焦点
        holdKeyboard: false, //输入框聚焦时，点击页面不收起键盘
    },

    onLoad: function (options) {
        let that = this;
        that.data.conversationID = options.conversationID;
        //获取会话资料
        let promise = app.$tim.getConversationProfile(options.conversationID);
        promise.then(function (imResponse) { //获取成功
            let data = imResponse.data.conversation; //会话资料
            console.log('获取会话资料成功：', data);
            let userID = data.userProfile.userID;
            wx.setNavigationBarTitle({ title: userID });
            that.data.userID = userID;
            that.getMsgList(); //拉取消息列表
        }).catch(function (imError) {
            console.warn('getConversationProfile error:', imError); //获取会话资料失败的相关信息
        });
    },

    onShow: function () {
        this.data.pageOnHide = false;
        if (this.data.pageOnHideNewMessage) {
            this.data.pageOnHideNewMessage = false;
            this.setMessageRead(); //已读上报
        }
    },

    onReady: function () {
        let that = this;
        //收到推送的单聊、群聊、群提示、群系统通知的新消息
        onMessageReceived = function (event) {
            // event.name - TIM.EVENT.MESSAGE_RECEIVED
            // event.data - 存储 Message 对象的数组 - [Message] 
            console.log('收到消息推送：', event);
            that.pushMessage(event.data[0]); //新消息上屏
            if (that.data.pageOnHide) {
                that.data.pageOnHideNewMessage = true;
            } else {
                that.setMessageRead(); //已读上报
            }
        };
        app.$tim.on(TIM.EVENT.MESSAGE_RECEIVED, onMessageReceived);

        //SDK 收到对端已读消息的通知，即已读回执。可通过遍历 event.data 获取对端已读的消息列表数据并渲染到页面，如单聊会话内可将己方发送的消息由“未读”状态改为“已读”。
        onMessageReadByPeer = function (event) {
            console.log('收到已读回执：', event);
            // event.data - 存储 Message 对象的数组 - [Message] - 每个 Message 对象的 isPeerRead 属性值为 true
            //设置已读 方法1 嵌套循环
            let data = event.data;
            let messageList = that.data.messageList;
            for (let a = 0; a < data.length; a++) {
                for (let b = 0; b < messageList.length; b++) {
                    if (data[a]['ID'] == messageList[b]['ID']) {
                        messageList[b]['isPeerRead'] = true;
                    }
                }
            }
            that.setData({ messageList: messageList });

            /* //设置已读 方法2 替换数组元素 (第一次进入会话时会收到一次已读回执，原因暂未排查)
            let dataLength = event.data.length;
            var index = parseInt('-' + dataLength);
            // console.log(index, dataLength);
            that.data.messageList.splice(index, dataLength, ...event.data);
            that.setData({ messageList: that.data.messageList }); */
        };
        app.$tim.on(TIM.EVENT.MESSAGE_READ_BY_PEER, onMessageReadByPeer);
    },

    onHide: function () {
        this.data.pageOnHide = true;
    },

    onUnload: function () {
        app.$tim.off(TIM.EVENT.MESSAGE_RECEIVED, onMessageReceived); //页面卸载时取消监听新消息推送
        app.$tim.off(TIM.EVENT.MESSAGE_READ_BY_PEER, onMessageReadByPeer); //取消监听已读回执
    },

    onPullDownRefresh: function () {
        if (this.data.isCompleted) {
            wx.stopPullDownRefresh(); //停止下拉刷新状态
            return;
        } else {
            this.getMsgList('load_more');
        }
    },

    //拉取消息列表
    getMsgList: function (type) {
        let that = this;
        let promise = app.$tim.getMessageList({ conversationID: that.data.conversationID, nextReqMessageID: that.data.nextReqMessageID, count: 15 });
        promise.then(function (imResponse) {
            console.log('拉取消息列表成功：', imResponse.data.messageList);
            that.data.nextReqMessageID = imResponse.data.nextReqMessageID; //用于续拉，分页续拉时需传入该字段。
            let isCompleted = imResponse.data.isCompleted; //表示是否已经拉完所有消息。
            let oldMessageList = imResponse.data.messageList; //返回的历史消息
            that.tackleMessage(oldMessageList, isCompleted, type); //处理消息
            wx.stopPullDownRefresh(); //停止下拉刷新状态
            if (type != 'load_more') {
                that.setMessageRead(); //已读上报
            }
        });
    },

    //处理消息
    tackleMessage: function (oldMessageList, isCompleted, type) {
        let newMessageList = [];
        for (let a = 0; a < oldMessageList.length; a++) {
            const msg = oldMessageList[a];
            if (msg.payload.text && msg.payload.text.indexOf('[') != -1) { //带有 [ 认为是有表情的消息
                newMessageList.push(tackleEmojiMessage(msg));
            } else {
                newMessageList.push(msg);
            }
        }
        let messageList = this.data.messageList;
        this.setData({ isCompleted: isCompleted, messageList: newMessageList.concat(messageList) });
        if (type != 'load_more') { //不是加载历史消息时，滚动到最后一条消息
            wx.pageScrollTo({ selector: '#' + newMessageList[newMessageList.length - 1]['ID'], duration: '0' });
        }
    },

    //将某会话下所有未读消息已读上报
    setMessageRead: function () {
        let promise = app.$tim.setMessageRead({ conversationID: this.data.conversationID });
        promise.then(function (imResponse) { //已读上报成功，指定 ID 的会话的 unreadCount 属性值被置为0
            console.log('已读上报成功：', imResponse);
        }).catch(function (imError) { //已读上报失败
            console.warn('setMessageRead error:', imError);
        });
    },

    //点击发送按钮
    clickSend: function () {
        let that = this;
        let msgContent = that.data.msgContent;
        if (msgContent == '') {
            wx.showToast({ icon: 'none', title: '请输入消息内容~' });
            return;
        }
        // 发送文本消息，Web 端与小程序端相同
        // 1. 创建消息实例，接口返回的实例可以上屏
        let message = app.$tim.createTextMessage({
            to: that.data.userID,
            conversationType: TIM.TYPES.CONV_C2C,
            payload: {
                text: msgContent
            }
        });
        that.sendMessage(message);
    },

    //发送消息
    sendMessage: function (message) {
        let that = this;
        let promise = app.$tim.sendMessage(message); //发送消息
        promise.then(function (imResponse) {
            console.log('发送成功：', imResponse);
            that.setData({ msgContent: '' }); //清空输入框
            that.pushMessage(imResponse.data.message); //新消息上屏
        }).catch(function (imError) {
            console.warn('sendMessage error:', imError);
        });
    },

    //新消息上屏
    pushMessage: function (msg) {
        let messageList = this.data.messageList;
        if (msg.payload.text && msg.payload.text.indexOf('[') != -1) { //带有 [ 认为是有表情的消息
            messageList.push(tackleEmojiMessage(msg));
        } else {
            messageList.push(msg);
        }
        this.setData({ messageList: messageList });
        wx.pageScrollTo({ selector: '#' + messageList[messageList.length - 1]['ID'] }); //滚动到最后一条消息
    },

    //输入框获取焦点
    setFocus: function () {
        this.setData({ setFocus: true, showEmojiBox: false });
    },

    //失去焦点
    bindblur: function () {

    },

    //输入框聚焦
    bindfocus: function () {
        this.data.showEmojiBox = false;
    },

    //输入消息
    inputChange: function (e) {
        this.data.msgContent = e.detail.value;
    },

    //显示选择表情
    showEmojiBox: function () {
        wx.hideKeyboard(); //收起键盘
        this.setData({ showEmojiBox: true });
        if (this.data.showEmojiBox) {
            wx.pageScrollTo({ selector: '#id_emoji_placeholder', duration: 0 }); //页面滚动到底部表情占位框
        }
    },

    //隐藏选择表情
    hiddenEmojiBox: function () {
        this.setData({ showEmojiBox: false });
    },

    //选择表情
    selectEmoji: function (e) {
        let emojiName = e.currentTarget.dataset.name;
        this.setData({ msgContent: this.data.msgContent += emojiName });
    },

    //选择相册
    selectPhoto: function () {
        let that = this;
        wx.chooseImage({
            sourceType: ['album'], // 从相册选择
            count: 1, // 只选一张，目前 SDK 不支持一次发送多张图片
            success: function (res) {
                console.log(res);
                let message = app.$tim.createImageMessage({
                    to: that.data.userID,
                    conversationType: TIM.TYPES.CONV_C2C,
                    payload: { file: res },
                    onProgress: function (event) { console.log('file uploading:', event) }
                });
                that.sendMessage(message);
            }
        })
    },

    //拍摄
    selectShoot: function () {
        let that = this;
        wx.chooseVideo({
            sourceType: ['album', 'camera'], // 来源相册或者拍摄
            maxDuration: 60, // 设置最长时间60s
            camera: 'back', // 后置摄像头
            success(res) {
                console.log(res);
                // 2. 创建消息实例，接口返回的实例可以上屏
                let message = app.$tim.createVideoMessage({
                    to: that.data.userID,
                    conversationType: TIM.TYPES.CONV_C2C,
                    // 消息优先级，用于群聊（v2.4.2起支持）。如果某个群的消息超过了频率限制，后台会优先下发高优先级的消息，详细请参考：https://cloud.tencent.com/document/product/269/3663#.E6.B6.88.E6.81.AF.E4.BC.98.E5.85.88.E7.BA.A7.E4.B8.8E.E9.A2.91.E7.8E.87.E6.8E.A7.E5.88.B6)
                    // 支持的枚举值：TIM.TYPES.MSG_PRIORITY_HIGH, TIM.TYPES.MSG_PRIORITY_NORMAL（默认）, TIM.TYPES.MSG_PRIORITY_LOW, TIM.TYPES.MSG_PRIORITY_LOWEST
                    // priority: TIM.TYPES.MSG_PRIORITY_NORMAL,
                    payload: {
                        file: res
                    },
                    // 消息自定义数据（云端保存，会发送到对端，程序卸载重装后还能拉取到，v2.10.2起支持）
                    // cloudCustomData: 'your cloud custom data'
                    // v2.12.2起，支持小程序端视频上传进度回调
                    onProgress: function (event) { console.log('file uploading:', event) }
                })
                that.sendMessage(message);
            }
        })
    },

})